package li.teng.android.xplanet;



import li.teng.android.xplanet.content.MyPosition;
import li.teng.android.xplanet.content.MyPositionHelper;
import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class PositionMap extends MapActivity implements SharedPreferences.OnSharedPreferenceChangeListener{
	private SharedPreferences sharedPreferences;
	MapController mapController;
	MapView mapView;// = (MapView) findViewById(R.id.map);
	
	static Location m_CurruntLocation;
	
	private final Handler uiHandler = new Handler();
	  private SensorManager sensorManager;
	  private LocationManager locationManager;
	  
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);
	    mapView = (MapView)findViewById(R.id.map);
	    mapController = mapView.getController();
	    sharedPreferences = getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0);
	    if (sharedPreferences != null) {
	      sharedPreferences.registerOnSharedPreferenceChangeListener(this);
	    }	
	    
	    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
	    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);	    
	    registerLocationAndSensorListeners();
	    m_CurruntLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);//.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//	    if(m_CurruntLocation == null){
//	    	
//	    }
	    mapController.setZoom(20);
	    setMapCenter(m_CurruntLocation);
	    mapView.setSatellite(true);
	    mapView.setBuiltInZoomControls(true);
    }
	
	  @Override
	  protected boolean isRouteDisplayed() {
	    return false;
	  }
	  @Override
	  protected boolean isLocationDisplayed() {
	    return true;
	  }
	  
	  @Override
	  public void onSharedPreferenceChanged(
	      final SharedPreferences sharedPreferences, final String key) {
	    Log.d(XplanetConstants.TAG,
	        "PositionWiki.onSharedPreferenceChanged: " + key);
	    if(key.equals(getString(R.string.min_recording_distance_key))){
	    	PositionList.m_Distance = sharedPreferences.getInt(getString(R.string.min_recording_distance_key), -1);
	    }
	    if (key != null) {
	      uiHandler.post(new Runnable() {
	        @Override
	        public void run() {
	          reloadSharedPreferences(sharedPreferences, key);
	        }
	      });
	    }
	  }
	  
	  private void reloadSharedPreferences(SharedPreferences sharedPreferences,String key) {
		    if(key.equals(getString(R.string.selected_track_key))){
		    	moveMapToLocation(sharedPreferences.getLong(
		    	          getString(R.string.selected_track_key),-1));
		    }
		    
	  }
	  private void setMapCenter(Location location){
		  if(location == null)return;
	      Double geoLat = location.getLatitude()*1E6;
	      Double geoLng = location.getLongitude()*1E6;
	      GeoPoint point = new GeoPoint(geoLat.intValue(),
	                                    geoLng.intValue());
	      mapController.setCenter(point);		  
	  }
	  private void moveMapToLocation(long id){
		  Log.d(XplanetConstants.TAG, "fly to " + id); 
		  MyPosition obj = MyPositionHelper.getInstance(this).getPosition(id);
		  if(obj != null){
		      Double geoLat = obj.getlatitude()*1E6;
		      Double geoLng = obj.getLogitude()*1E6;
		      GeoPoint point = new GeoPoint(geoLat.intValue(),
		                                    geoLng.intValue());
		      mapController.setCenter(point);
		  }else{
			  Log.d(XplanetConstants.TAG, "no place is assigened fly to "); 
		  }
	  }

	  private final LocationListener locationListener = new LocationListener() {
		    @Override
		    public void onProviderEnabled(String provider) {
		      if (provider.equals(XplanetConstants.GPS_PROVIDER)) {

		      }
		    }

		    @Override
		    public void onProviderDisabled(String provider) {
		      if (provider.equals(XplanetConstants.GPS_PROVIDER)) {

		      }
		    }

		    @Override
		    public void onLocationChanged(Location location) {
		      if (location.getProvider().equals(XplanetConstants.GPS_PROVIDER)) {
		    	  Log.d(XplanetConstants.TAG, "PositionMap onLocationChanged");
		    	  m_CurruntLocation = location;
		      } else {

		      }
		    }

		    @Override
		    public void onStatusChanged(String provider, int status, Bundle extras) {
		      if (provider.equals(XplanetConstants.GPS_PROVIDER)) {
		        switch (status) {
		          case LocationProvider.OUT_OF_SERVICE:
		          case LocationProvider.TEMPORARILY_UNAVAILABLE:
		            break;
		        }
		      }
		    }
		  };

		  private final SensorEventListener sensorListener = new SensorEventListener() {
		    @Override
		    public void onSensorChanged(SensorEvent se) {
		      synchronized (this) {
		        float magneticHeading = se.values[0];
		      }
		    }

		    @Override
		    public void onAccuracyChanged(Sensor s, int accuracy) {
		    }
		  };
		  
		  public void alert(String txt) {
			    Toast.makeText(this, txt, Toast.LENGTH_LONG).show();
		  }
	  
	  void registerLocationAndSensorListeners() {
		  Log.d(XplanetConstants.TAG,"registerLocationAndSensorListeners");
		    if (locationManager != null) {
		      LocationProvider gpsProvider =
		          locationManager.getProvider(XplanetConstants.GPS_PROVIDER);
		      if (gpsProvider == null) {
		        alert(getString(R.string.missing_gps));
		        return;
		      } else {
		        Log.d(XplanetConstants.TAG, "MyTracksMap: Using location provider "
		            + gpsProvider.getName());
		      }
		      locationManager.requestLocationUpdates(gpsProvider.getName(),
		          0 /*minTime*/, 0 /*minDist*/, locationListener);
		      try {
		        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
		            1000 * 60 * 5 /*minTime*/, 0 /*minDist*/, locationListener);
		      } catch (RuntimeException e) {
		        // If anything at all goes wrong with getting a cell location do not
		        // abort. Cell location is not essential to this app.
		        Log.w(XplanetConstants.TAG,
		            "Could not register network location listener.");
		      }
		    }
		    if (sensorManager == null) {
		      return;
		    }
		    Sensor compass = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
		    if (compass == null) {
		      return;
		    }
		    Log.d(XplanetConstants.TAG,"Now registering sensor listeners.");
		    sensorManager.registerListener(sensorListener, compass, SensorManager.SENSOR_DELAY_UI);
		  }
	  
	  void unregisterLocationAndSensorListeners() {
		    if (locationManager != null) {
		      locationManager.removeUpdates(locationListener);
		    }
		    if (sensorManager != null) {
		      sensorManager.unregisterListener(sensorListener);
		    }
		  }
}
